<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList()"
            size="small">
          查询
        </el-button>
        <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch()"
            size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" label-width="auto" size="small">
          <el-form-item label="数据源：">
            <el-select v-model="listQuery.datasourceId" style="width:100%" filterable @change="getList()">
              <el-option
                  v-for="item in datasourceOption"
                  :key="item.id"
                  :label="item.remark"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="warning" size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加
      </el-button>
    </el-card>

    <div class="table-container">
      <el-table :default-sort="{prop: 'name', order: 'descending'}"
                :data="list"
                style="width: 100%;" border>
        <el-table-column label="表名" align="center" prop="tableName" sortable/>
        <el-table-column align="center" label="数据量" prop="tableRows" sortable width="100"/>
        <el-table-column label="创建时间" align="center" prop="createTime" sortable width="180"/>
        <!--        <el-table-column label="更新时间" align="center" prop="updateTime" sortable width="180"/>-->
        <el-table-column label="编码" align="center" prop="tableCollation" sortable/>
        <el-table-column label="表说明" align="center" prop="tableComment" show-overflow-tooltip/>

        <el-table-column align="center" fixed="right" label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="success"
                       @click="handleShowField(scope.row)">字段管理
            </el-button>
            <el-button size="mini"
                       type="warning"
                       @click="handleUpdateTable(scope.row)">编辑
            </el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDeleteTable(scope.row.tableName)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="'表【'+currentSelectTable.tableName+'】 - 字段管理'"
               :visible.sync="tableFieldDialogVisible"
               width="80%">
      <div style="width: 100%;margin: 10px;text-align: right">
        <el-button type="primary" size="mini" @click="addTableField">新增</el-button>
      </div>
      <el-table :data="currentSelectTable.fieldNames"
                style="width: 100%;" border>
        <el-table-column label="字段名" align="center" prop="name" sortable/>
        <el-table-column label="类型" align="center" prop="type" sortable/>
        <el-table-column label="描述" align="center" prop="desc"/>
        <el-table-column label="键" align="center" prop="key" sortable/>
        <el-table-column label="扩展信息" align="center" prop="extra" sortable/>
        <el-table-column label="java字段名" align="center" prop="javaName" sortable/>
        <el-table-column label="java类型" align="center" prop="javaType" sortable/>
        <el-table-column label="操作" align="center" width="260" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="warning"
                       @click="handleEditField(scope.row)">编辑
            </el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDeleteField(scope.row)">删除
            </el-button>
            <el-button size="mini"
                       type="success"
                       @click="jumpToTableFieldConfig(scope.row.name)">映射配置
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
          <el-button @click="tableFieldDialogVisible = false" size="small">取 消</el-button>
        </span>
    </el-dialog>

    <el-dialog title="新增数据表" :visible.sync="addTableDialogVisible" width="80%">
      <div style="color:red;white-space: pre-wrap;">使用指引：
        1、通过辅助建表工具，填写表名、字段、注释等信息
        2、点击生成建表SQL按钮，获取建表SQL，检查生成的SQL是否正确
        3、提交SQL，新增数据表
        4、如果已有建表SQL，直接粘贴到建表sql框，提交即可
      </div>
      <el-collapse :value="'1'">
        <el-collapse-item title="建表辅助工具" name="0">
          <el-tabs value="first">
            <el-tab-pane label="字段" name="first">
              <el-form :inline="true" label-suffix="：" label-width="auto" size="small">
                <el-form-item label="数据表名">
                  <el-input v-model="addTableName" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="数据库引擎">
                  <el-input v-model="addTableEngine" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="编码">
                  <el-input v-model="addTableCharset" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="注释">
                  <el-input type="textarea" autosize v-model="addTableComment" size="mini"></el-input>
                </el-form-item>
              </el-form>
              <div style="width: 100%;text-align: right;padding: 10px 0">
                <el-button type="primary" size="mini" @click="addOneField">新增字段</el-button>
              </div>
              <el-table :data="createTableSqlByToolsArr"
                        style="width: 100%;" border>

                <el-table-column label="字段名" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.fieldName" clearable
                              @change="(fieldName)=>fieldNameChange(fieldName,scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column label="数据类型" align="center">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.fieldType" filterable placeholder="请选择"
                               @change="(v)=>{fieldTypeChange(v,scope.row)}">
                      <el-option-group
                          v-for="group in fieldTypeOptions"
                          :key="group.label"
                          :label="group.label">
                        <el-option
                            v-for="item in group.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-option-group>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="长度" align="center" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.fieldLen" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="是否必填" align="center" width="165">
                  <template slot-scope="scope">
                    <el-switch
                        active-value="1"
                        inactive-value="0"
                        v-model="scope.row.nullable"
                        active-text="必填"
                        inactive-text="非必填">
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="默认值" align="center">
                  <template slot-scope="scope">
                    <el-select clearable placeholder="可自定义输入"
                               v-model="scope.row.defaultValue"
                               @change="(v)=>defaultValueChange(v,scope.row)"
                               filterable
                               allow-create
                               default-first-option>
                      <el-option
                          v-for="item in defaultValueOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          :disabled="scope.row.nullable =='1' && item.value=='NULL'">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="注释" align="center">
                  <template slot-scope="scope">
                    <el-input type="textarea" autosize v-model="scope.row.fieldDesc" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="80">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger"
                               @click="handleDeleteOneField(scope.row.myIndex)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="排序" align="center" width="140">
                  <template slot-scope="scope">
                    <el-button size="mini" type="success"
                               @click="handleFieldSort(scope.row.myIndex,-1)">
                      ⬆
                    </el-button>
                    <el-button size="mini" type="warning"
                               @click="handleFieldSort(scope.row.myIndex,1)">
                      ⬇
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="索引" name="second">
              <div style="width: 100%;text-align: right;padding: 10px 0">
                <el-button type="primary" size="mini" @click="addOneFieldIndex">新增索引</el-button>
              </div>

              <el-table :data="createTableSqlByToolsIndexArr"
                        style="width: 100%;" border>

                <el-table-column label="索引名称" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.indexName" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="索引类型" align="center">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.indexType" placeholder="请选择" style="width: 100%;"
                               filterable>
                      <el-option
                          v-for="item in fieldIndexoptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="字段" align="center">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.indexField" placeholder="请选择" multiple filterable
                               style="width: 100%;"
                               @change="(arr)=>indexFieldChange(arr,scope.row)">
                      <el-option
                          v-for="item in createTableSqlByToolsArr"
                          :key="item.fieldName"
                          :label="item.fieldName"
                          :value="item.fieldName">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="操作" align="center" width="80">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger"
                               @click="handleDeleteOneFieldIndex(scope.row.myIndex)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>

              </el-table>

            </el-tab-pane>
          </el-tabs>
          <div style="width: 100%;text-align: right;padding: 10px 0">
            <el-button @click="createTableSqlByTools" type="primary">生成建表sql</el-button>
          </div>
        </el-collapse-item>
        <el-collapse-item title="建表sql" name="1">
          <el-input type="textarea" :autosize="{ minRows: 10, maxRows: 30}" v-model="createTableSql"
                    clearable></el-input>
        </el-collapse-item>
      </el-collapse>
      <span slot="footer" class="dialog-footer">
           <el-button @click="confirmAddTable" size="small" type="primary">执行建表sql</el-button>
            <el-button @click="addTableDialogVisible = false" size="small">取 消</el-button>
        </span>
    </el-dialog>

    <el-dialog :title="editTableFieldDialogFlag?'编辑数据表字段':'新增数据表字段'"
               :visible.sync="alterTableFieldDialogVisible" width="60%">

      <el-steps direction="vertical" :active="addOrEditStep">
        <el-step title="步骤 1：编辑字段基本信息" >
          <el-form slot="description" label-suffix="：" label-width="auto" size="small">
            <el-form-item label="字段名">
              <el-input v-model="alterTableFieldRow.fieldName" clearable/>
            </el-form-item>
            <el-form-item label="数据类型">
              <el-select v-model="alterTableFieldRow.fieldType" filterable placeholder="请选择" style="width: 100%">
                <el-option-group
                    v-for="group in fieldTypeOptions"
                    :key="group.label"
                    :label="group.label">
                  <el-option
                      v-for="item in group.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="长度">
              <el-input v-model="alterTableFieldRow.fieldLen" clearable/>
            </el-form-item>
            <el-form-item label="是否必填">
              <el-switch
                  active-value="1"
                  inactive-value="0"
                  v-model="alterTableFieldRow.nullable"
                  active-text="必填"
                  inactive-text="非必填">
              </el-switch>
            </el-form-item>
            <el-form-item label="默认值">
              <el-select clearable placeholder="可自定义输入" style="width: 100%"
                         v-model="alterTableFieldRow.defaultValue"
                         filterable
                         allow-create
                         default-first-option>
                <el-option
                    v-for="item in defaultValueOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="alterTableFieldRow.nullable =='1' && item.value=='NULL'">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="注释">
              <el-input type="textarea" autosize v-model="alterTableFieldRow.fieldDesc" clearable/>
            </el-form-item>
            <el-form-item label="生成修改的sql语句">
              <el-button type="success" @click="createAlterTableSql">生成sql</el-button>
            </el-form-item>
          </el-form>
        </el-step>
        <el-step title="步骤 2：确认sql语句是否正确" >
          <div slot="description">
          <div><span style="color: red">对于索引的修改，需要手动编写sql</span></div>
          <el-input type="textarea" :autosize="{ minRows: 10, maxRows: 30}" v-model="alterTableSql"
                    clearable></el-input>

          </div>
        </el-step>
        <el-step title="步骤 3：提交/取消" >
           <span slot="description" class="dialog-footer">
            <el-button @click="confirmAlterTableField" size="small" type="primary">执行sql语句</el-button>
            <el-button @click="alterTableFieldDialogVisible = false" size="small">取 消</el-button>
            </span>
        </el-step>
      </el-steps>
    </el-dialog>

    <el-dialog :visible.sync="editDialogVisible"
               title="编辑数据表" width="30%">
      <el-form :model="editTableRow" label-suffix="：" label-width="auto" size="small">
        <el-form-item label="表名" required>
          <el-input v-model="editTableRow.tableName" clearable @input="forceUpdateElement"/>
        </el-form-item>
        <el-form-item label="表注释">
          <el-input v-model="editTableRow.tableDesc" clearable @input="forceUpdateElement"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
           <el-button size="small" type="primary" @click="confirmEditTable">提交</el-button>
            <el-button size="small" @click="editDialogVisible = false">取 消</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import {tablePostRequire} from '@/api/tableConfig'
import {projectDatasourcePostRequire} from '@/api/projectDatasource'

const defaultCreateTableColumn = [
  {
    myIndex: '0',
    defaultValue: '自增',
    fieldType: 'INT',
    fieldLen: '11',
    fieldName: 'id',
    nullable: '1',
    fieldDesc: '自增id',
  }, {
    myIndex: '1',
    defaultValue: 'NULL',
    fieldType: 'VARCHAR',
    fieldLen: '50',
    fieldName: 'creator',
    nullable: '0',
    fieldDesc: '创建人',
  }, {
    myIndex: '2',
    defaultValue: 'NULL',
    fieldType: 'VARCHAR',
    fieldLen: '50',
    fieldName: 'updater',
    nullable: '0',
    fieldDesc: '更新人',
  }, {
    myIndex: '3',
    defaultValue: '无默认值',
    fieldType: 'DATETIME',
    fieldLen: '',
    fieldName: 'create_time',
    nullable: '1',
    fieldDesc: '创建时间',
  }, {
    myIndex: '4',
    defaultValue: 'NULL',
    fieldType: 'DATETIME',
    fieldLen: '',
    fieldName: 'update_time',
    nullable: '0',
    fieldDesc: '更新时间',
  },

]

const defaultListQuery = {
  datasourceId: undefined,
}
const defaultTable = {
  tableName: undefined,
  tableRows: undefined,
  createTime: undefined,
  updateTime: undefined,
  tableCollation: undefined,
  tableComment: undefined,
  fieldNames: []
}
export default {
  name: 'tableFieldList',
  data() {
    return {
      editTableRow: {},
      editDialogVisible: false,
      listQuery: this.$deepClone(defaultListQuery),
      list: null,
      listLoading: false,
      tableFieldDialogVisible: false,
      project: this.$deepClone(defaultTable),
      datasourceOption: [],

      currentDatasource: '',
      currentSelectTable: {},

      addTableDialogVisible: false,
      createTableSql: '',
      createTableSqlByToolsArr: [...this.$deepClone(defaultCreateTableColumn)],
      createTableSqlByToolsIndexArr: [{
        myIndex: new Date().getTime() + '',
        indexType: 'PRIMARY KEY',
        indexName: 'id',
        indexField: ['id'],
      }],
      fieldTypeOptions: [
        {
          label: '数值',
          options: [
            {
              value: 'BIT',
              label: 'BIT',
              len: '1'
            }, {
              value: 'TINYINT',
              label: 'TINYINT',
              len: '3'
            }, {
              value: 'SMALLINT',
              label: 'SMALLINT',
              len: '5'
            }, {
              value: 'MEDIUMINT',
              label: 'MEDIUMINT',
              len: '8'
            }, {
              value: 'INT',
              label: 'INT',
              len: '11'
            }, {
              value: 'BIGINT',
              label: 'BIGINT',
              len: '20'
            }, {
              value: 'FLOAT',
              label: 'FLOAT'
            }, {
              value: 'DOUBLE',
              label: 'DOUBLE'
            }, {
              value: 'DECIMAL',
              label: 'DECIMAL',
              len: '20,6'
            }]
        }, {
          label: '字符串',
          options: [
            {
              value: 'CHAR',
              label: 'CHAR',
              len: '1'
            }, {
              value: 'VARCHAR',
              label: 'VARCHAR',
              len: '32'
            }, {
              value: 'TINYTEXT',
              label: 'TINYTEXT'
            }, {
              value: 'TEXT',
              label: 'TEXT'
            }, {
              value: 'MEDIUMTEXT',
              label: 'MEDIUMTEXT'
            }, {
              value: 'LONGTEXT',
              label: 'LONGTEXT'
            }, {
              value: 'JSON',
              label: 'JSON'
            }, {
              value: 'UUID',
              label: 'UUID'
            }]
        }, {
          label: '二进制文件',
          options: [
            {
              value: 'BINARY',
              label: 'BINARY',
              len: '32'
            }, {
              value: 'VARBINARY',
              label: 'VARBINARY',
              len: '32'
            }, {
              value: 'TINYBLOB',
              label: 'TINYBLOB'
            }, {
              value: 'BLOB',
              label: 'BLOB'
            }, {
              value: 'MEDIUMBLOB',
              label: 'MEDIUMBLOB'
            }, {
              value: 'LONGBLOB',
              label: 'LONGBLOB'
            }]
        }, {
          label: '时间和日期',
          options: [
            {
              value: 'DATE',
              label: 'DATE'
            }, {
              value: 'TIME',
              label: 'TIME'
            }, {
              value: 'YEAR',
              label: 'YEAR'
            }, {
              value: 'DATETIME',
              label: 'DATETIME'
            }, {
              value: 'TIMESTAMP',
              label: 'TIMESTAMP'
            }]
        }],
      defaultValueOptions: [
        {
          label: '无默认值',
          value: '无默认值'
        }, {
          label: 'NULL',
          value: 'NULL'
        }, {
          label: '自增(主键)',
          value: '自增'
        }],
      fieldIndexoptions: [
        {
          value: 'INDEX',
          label: '普通索引',
        }, {
          value: 'UNIQUE INDEX',
          label: '唯一索引',
        }, {
          value: 'PRIMARY KEY',
          label: '主键',
        }],
      addTableName: 'example',
      addTableComment: '',
      addTableEngine: 'InnoDB',
      addTableCharset: 'utf8',

      alterTableFieldDialogVisible: false,
      editTableFieldDialogFlag: true,
      alterTableFieldRow: {},
      alterTableFieldOriRow: {},
      alterTableSql: '',

      addOrEditStep:1
    }
  },
  created() {
    let currentProject = JSON.parse((localStorage.getItem('currentProject') || "{}"))
    if (currentProject) {
      this.listQuery.datasourceId = currentProject.datasourceId || ''
    }
    this.getDatasourceList()
    this.getList()
  },
  methods: {
    forceUpdateElement() {
      this.$forceUpdate()
    },
    handleUpdateTable(row) {
      this.editTableRow.oldTableName = row.tableName
      this.editTableRow.tableDesc = row.tableComment
      this.editTableRow.tableName = row.tableName
      this.editDialogVisible = true
    },
    confirmEditTable() {
      let tableName = this.editTableRow.tableName
      let tableDesc = this.editTableRow.tableDesc
      if (!tableName) {
        this.$message({
          type: 'error',
          message: '请填写表名'
        })
      } else {
        this.listLoading = true
        tablePostRequire('editTableInfo', {
          oldTableName: this.editTableRow.oldTableName,
          tableDesc: tableDesc,
          tableName: tableName,
          datasourceId: this.currentDatasource
        }).then(response => {
          if (response) {
            this.$message({
              type: 'success',
              message: response.message
            })
          }
          this.editDialogVisible = false
          this.listLoading = false
          this.refreshCache()
        })
      }
    },
    jumpToTableFieldConfig(filedName) {
      let query = {
        tableName: this.currentSelectTable.tableName,
        filedName: filedName
      }
      let currentProject = JSON.parse((localStorage.getItem('currentProject') || "{}"))
      if (currentProject) {
        query.projectId = currentProject.id;
      }
      query.datasourceId = this.currentDatasource
      const routeUrl = this.$router.resolve({
        path: '/project/tableFieldConfig',
        query: query
      })
      window.open(routeUrl.href, '_blank')
    },
    handleDeleteField(row) {
      this.$confirm('确定删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let sql = "ALTER TABLE `" + this.currentSelectTable.tableName + "` " +
            "DROP COLUMN `" + row.name + "`;"
        tablePostRequire('update', {
          sql: sql,
          datasourceId: this.currentDatasource,
          tableName: this.currentSelectTable.tableName
        }).then(response => {
          if (response) {
            this.$message({
              type: 'success',
              message: response.message
            })
          }
          this.tableFieldDialogVisible = false
          this.refreshCache()
        })
      })
    },
    addTableField() {
      this.alterTableSql = ''
      this.alterTableFieldRow = {
        defaultValue: '无默认值',
        fieldType: 'VARCHAR',
        fieldLen: '32',
        nullable: '0'
      }
      this.editTableFieldDialogFlag = false
      this.alterTableFieldDialogVisible = true
    },
    confirmAlterTableField() {
      if (!this.alterTableSql) {
        this.$message({
          type: 'warning',
          message: '执行修改的sql为空!'
        })
        return
      }
      tablePostRequire('update', {
        sql: this.alterTableSql,
        datasourceId: this.currentDatasource,
        tableName: this.currentSelectTable.tableName
      }).then(response => {
        if (response) {
          this.$message({
            type: 'success',
            message: response.message
          })
        }
        this.alterTableFieldDialogVisible = false
        this.refreshCache()
      })
    },
    createAlterTableSql() {
      this.addOrEditStep = 2
      let noNeedLenStrict = [
        'DATE',
        'DATETIME',
        'TIMESTAMP',
        'TIME',
        'YEAR',
        'BOOLEAN',
        'BOOL' // BOOLEAN 的别名
      ];
      let alterTableSql = ''
      let alterTableFieldRow = this.alterTableFieldRow
      let alterTableFieldOriRow = this.alterTableFieldOriRow
      if (this.editTableFieldDialogFlag) {
        let keys = Object.keys(alterTableFieldOriRow)
        let hasChange = false
        for (let i = 0; i < keys.length; i++) {
          if (alterTableFieldRow[keys[i]] != alterTableFieldOriRow[keys[i]]) {
            hasChange = true
            break
          }
        }
        if (!hasChange) {
          this.$message({
            type: 'warning',
            message: '无改动!'
          })
          return
        }
        alterTableSql = 'ALTER TABLE `' + this.currentSelectTable.tableName + "`\r\n" +
            '  CHANGE COLUMN `' + alterTableFieldOriRow.fieldName + "` `" +
            alterTableFieldRow.fieldName + "` " + alterTableFieldRow.fieldType;
        if (alterTableFieldRow.fieldLen && !noNeedLenStrict.includes(alterTableFieldRow.fieldType)) {
          alterTableSql += "(" + alterTableFieldRow.fieldLen + ")"
        }
        if (alterTableFieldRow.nullable == '0') {
          alterTableSql += " NULL"
        } else {
          alterTableSql += " NOT NULL"
        }
        if (alterTableFieldRow.defaultValue == 'NULL') {
          alterTableSql += " DEFAULT NULL"
        } else if (alterTableFieldRow.defaultValue == '自增') {
          alterTableSql += " AUTO_INCREMENT"
        } else if (alterTableFieldRow.defaultValue != '无默认值') {
          alterTableSql += " DEFAULT '" + alterTableFieldRow.defaultValue + "'"
        }
        if (alterTableFieldRow.fieldDesc) {
          alterTableSql += " COMMENT '" + alterTableFieldRow.fieldDesc.split("\n").join("\\r\\n") + "';"
        }
      } else {
        alterTableSql = 'ALTER TABLE `' + this.currentSelectTable.tableName + "`\r\n" +
            '  ADD COLUMN `' + alterTableFieldRow.fieldName + "` " + alterTableFieldRow.fieldType;
        if (alterTableFieldRow.fieldLen && !noNeedLenStrict.includes(alterTableFieldRow.fieldType)) {
          alterTableSql += "(" + alterTableFieldRow.fieldLen + ")"
        }
        if (alterTableFieldRow.nullable == '0') {
          alterTableSql += " NULL"
        } else {
          alterTableSql += " NOT NULL"
        }
        if (alterTableFieldRow.defaultValue == 'NULL') {
          alterTableSql += " DEFAULT NULL"
        } else if (alterTableFieldRow.defaultValue == '自增') {
          alterTableSql += " AUTO_INCREMENT"
        } else if (alterTableFieldRow.defaultValue != '无默认值') {
          alterTableSql += " DEFAULT '" + alterTableFieldRow.defaultValue + "'"
        }
        if (alterTableFieldRow.fieldDesc) {
          alterTableSql += " COMMENT '" + alterTableFieldRow.fieldDesc.split("\n").join("\\r\\n") + "';"
        }
      }

      this.alterTableSql = alterTableSql
    },
    handleEditField(row) {
      this.addOrEditStep = 1
      let fieldType = row.type
      let fieldLen = ''
      if (fieldType.indexOf("(") != -1) {
        fieldLen = fieldType.substring(fieldType.indexOf("(") + 1)
        fieldLen = fieldLen.split("(").join("").split(")").join("")
        fieldType = fieldType.substring(0, fieldType.indexOf("("))
      }
      fieldType = fieldType.toUpperCase()

      let nullable = '0'//非必填
      if (row.notNull) {
        nullable = '1'
      }

      let defaultValue = 'NULL'
      if (row.extra == 'auto_increment') {
        defaultValue = '自增'
      } else if (row.defaultValue) {
        defaultValue = row.defaultValue
      }

      let alterTableFieldRow = {
        fieldName: row.name,
        fieldLen: fieldLen,
        fieldType: fieldType,
        nullable: nullable,
        fieldDesc: row.desc,
        defaultValue: defaultValue
      }
      this.alterTableFieldRow = alterTableFieldRow
      this.alterTableFieldOriRow = this.$deepClone(alterTableFieldRow)
      this.alterTableSql = ''
      this.editTableFieldDialogFlag = true
      this.alterTableFieldDialogVisible = true
    },
    fieldNameChange(fieldName, row) {
      if (fieldName == 'id') {
        row.defaultValue = '自增'
        row.fieldType = 'INT'
        row.fieldLen = '11'
        row.nullable = '1'
        row.fieldDesc = '自增主键'
        this.defaultValueChange('自增', row)
      }
    },
    indexFieldChange(arr, row) {
      if (!row.indexName) {
        row.indexName = arr[0]
      }
    },
    defaultValueChange(value, row) {
      if (value == '自增') {
        let createTableSqlByToolsIndexArr = this.createTableSqlByToolsIndexArr || []
        for (let i = 0; i < createTableSqlByToolsIndexArr.length; i++) {
          if (createTableSqlByToolsIndexArr[i].indexField.toString() == row.fieldName) {
            createTableSqlByToolsIndexArr.splice(i, 1)
            break
          }
        }
        this.createTableSqlByToolsIndexArr.splice(0, 0, {
          myIndex: new Date().getTime() + '',
          indexType: 'PRIMARY KEY',
          indexName: row.fieldName,
          indexField: [row.fieldName],
        })
        row.nullable = '1'
      }
    },
    createTableSqlByTools() {
      let sql = 'CREATE TABLE `' + this.addTableName + "` (\r\n"
      let createTableSqlByToolsArr = this.createTableSqlByToolsArr
      for (let i = 0; i < createTableSqlByToolsArr.length; i++) {
        let field = createTableSqlByToolsArr[i]
        sql += '  `' + field.fieldName + '` ' + field.fieldType
        if (field.fieldLen) {
          sql += "(" + field.fieldLen + ")"
        }
        if (field.nullable == '0') {
          sql += " NULL"
        } else {
          sql += " NOT NULL"
        }
        if (field.defaultValue == 'NULL') {
          sql += " DEFAULT NULL"
        } else if (field.defaultValue == '自增') {
          sql += " AUTO_INCREMENT"
        } else if (field.defaultValue != '无默认值') {
          sql += " DEFAULT '" + field.defaultValue + "'"
        }
        if (field.fieldDesc) {
          sql += " COMMENT '" + field.fieldDesc.split("\n").join("\\r\\n") + "'"
        }
        sql += ",\r\n"
      }

      let createTableSqlByToolsIndexArr = this.createTableSqlByToolsIndexArr || []
      for (let i = 0; i < createTableSqlByToolsIndexArr.length; i++) {
        let index = createTableSqlByToolsIndexArr[i]
        sql += "  " + index.indexType
        if (index.indexType != 'PRIMARY KEY') {
          sql += " `" + index.indexName + "`"
        }

        let indexFieldArr = index.indexField || []
        if (indexFieldArr.length > 0) {
          sql += " ("
          for (let j = 0; j < indexFieldArr.length; j++) {
            sql += " `" + indexFieldArr[j] + "`,"
          }
          sql = sql.substring(0, sql.length - 1)
          sql += " )"
        }

        if (index.indexType == 'PRIMARY KEY') {
          sql += "  USING BTREE"
        }

        if (i < createTableSqlByToolsIndexArr.length - 1) {
          sql += ",\r\n"
        }
      }
      sql += "\r\n)\r\n";
      let addTableComment = this.addTableComment
      addTableComment = addTableComment.split("\n").join("\\r\\n")
      sql +=
          "COMMENT='" + addTableComment + "'\n" +
          "CHARSET='" + this.addTableCharset + "'\n" +
          "ENGINE=" + this.addTableEngine + "\n" +
          ";\n";

      this.createTableSql = sql
    },
    addOneField() {
      let arr = this.createTableSqlByToolsArr || []
      let index = arr.length - 1
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].fieldName == 'creator') {
          index = i
          break
        }
      }
      this.createTableSqlByToolsArr.splice(index, 0, {
        myIndex: new Date().getTime() + '',
        defaultValue: '无默认值',
        fieldType: 'VARCHAR',
        fieldLen: '32',
        nullable: '0'
      })
    },
    addOneFieldIndex() {
      this.createTableSqlByToolsIndexArr.push({myIndex: new Date().getTime() + '', indexType: 'INDEX'})
    },
    handleDeleteOneFieldIndex(myIndex) {
      let createTableSqlByToolsArr = this.createTableSqlByToolsIndexArr
      let index
      for (let i = 0; i < createTableSqlByToolsArr.length; i++) {
        if (createTableSqlByToolsArr[i].myIndex == myIndex) {
          index = i;
          break;
        }
      }
      createTableSqlByToolsArr.splice(index, 1)
    },
    handleFieldSort(myIndex, offest) {
      let createTableSqlByToolsArr = this.createTableSqlByToolsArr
      let index
      for (let i = 0; i < createTableSqlByToolsArr.length; i++) {
        if (createTableSqlByToolsArr[i].myIndex == myIndex) {
          index = i;
          break;
        }
      }
      if (index == 0 && offest == -1) {
        return;
      }
      if (index == createTableSqlByToolsArr.length - 1 && offest == 1) {
        return;
      }
      let deleteOne = createTableSqlByToolsArr.splice(index, 1)[0]
      index += offest
      createTableSqlByToolsArr.splice(index, 0, deleteOne)
      // this.createTableSqlByToolsArr = createTableSqlByToolsArr
    },
    fieldTypeChange(value, row) {
      let fieldTypeOptions = this.fieldTypeOptions
      let options = []
      fieldTypeOptions.forEach(fo => {
        options.push(...(fo.options))
      })
      for (let i = 0; i < options.length; i++) {
        if (value == options[i].value) {
          if (options[i].len) {
            row.fieldLen = options[i].len
          } else {
            row.fieldLen = ''
          }
          break;
        }
      }
    },
    handleDeleteOneField(myIndex) {
      let createTableSqlByToolsArr = this.createTableSqlByToolsArr
      let index
      for (let i = 0; i < createTableSqlByToolsArr.length; i++) {
        if (createTableSqlByToolsArr[i].myIndex == myIndex) {
          index = i;
          break;
        }
      }
      createTableSqlByToolsArr.splice(index, 1)
    },
    confirmAddTable() {
      if (!this.createTableSql) {
        this.$message({
          message: '请先生成建表语句!',
          type: 'error'
        })
      }else {
        tablePostRequire('add', {
          addSql: this.createTableSql,
          datasourceId: this.currentDatasource,
          tableName: this.addTableName
        }).then(response => {
          if (response) {
            this.$message({
              type: 'success',
              message: response.message
            })
          }
          this.addTableDialogVisible = false
          this.refreshCache()
        })
      }
    },
    handleAdd() {
      if (!this.listQuery.datasourceId) {
        this.$message({
          message: '请先选择数据源',
          type: 'error'
        })
        return false;
      }
      this.createTableSql = ''
      this.addTableDialogVisible = true;
    },
    handleShowField(row) {
      this.currentSelectTable = this.$deepClone(row);
      this.tableFieldDialogVisible = true;
    },
    handleDeleteTable(tableName) {
      this.$confirm('该表数据将会一并删除且不可恢复，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        tablePostRequire('delete', {
          tableName: tableName,
          datasourceId: this.currentDatasource
        }).then(response => {
          if (response) {
            this.$message({
              type: 'success',
              message: response.message
            })
          }
          this.refreshCache()
        })
      })
    },
    handleResetSearch() {
      this.listQuery = this.$deepClone(defaultListQuery)
    },
    handleSearchList() {
      this.getList()
    },
    getList() {
      if (!this.listQuery.datasourceId) {
        this.$message({
          message: '请先选择数据源',
          type: 'error'
        })
      } else {
        this.currentDatasource = this.listQuery.datasourceId
        this.listLoading = true
        tablePostRequire('listAll', {datasourceId: this.listQuery.datasourceId}).then(response => {
          this.list = response.data || []
          if (this.list.length > 0 && this.currentSelectTable) {
            let tableName = this.currentSelectTable.tableName
            for (let i = 0; i < this.list.length; i++){
              if (this.list[i].tableName === tableName) {
                this.currentSelectTable = this.list[i]
                break;
              }
            }
          }
        }).finally(() => {
          this.listLoading = false
        })
      }
    },
    refreshCache() {
      let currentProject = JSON.parse((localStorage.getItem('currentProject') || "{}"))
      if (!this.listQuery.datasourceId && currentProject) {
        this.listQuery.datasourceId = currentProject.datasourceId || ''
      }
      this.getList()
    },
    getDatasourceList() {
      projectDatasourcePostRequire('listAll').then(response => {
        this.datasourceOption = response.data || []
      })
    },
  }
}
</script>
<style>
.demo-table-expand label {
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-left: 10px;
  width: 100%;
}
</style>
